<template>
  <el-form
    @submit.prevent
    style="margin: 20px 0"
    :model="formData"
    ref="ruleForm"
    label-width="100px"
  >
    <el-row :gutter="20">
      <el-col :span="span" v-for="field in fields" :key="field.value">
        <el-form-item :label="field.label" :prop="field.value" :label-width="field.width">
          <slot v-if="field.slot" :name='field.value' :item="formData"></slot>
          <component
            v-else
            :is="field.type || 'el-input'"
            v-bind="field.props"
            v-model="formData[field.value]"
            style="width: 100%"
          >
            <template v-if="field.type === 'el-select'">
              <el-option
                v-for="item in field.props.options"
                :key="item[field.props.valueKey] || item.value"
                :label="item[field.props.labelKey] ||item.label"
                :value="item[field.props.valueKey] || item.value"
              />
            </template>
          </component>
        </el-form-item>
      </el-col>
      <!-- 重点样式 margin-left / margin-right :auto -->
      <el-col :span="span" style="margin-left: auto; text-align: right">
        <el-button type="primary" @click="submitForm">查询</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-col>
    </el-row>
  </el-form>
</template>

<script lang='ts'>
import { deepClone } from '@/utils'
import { defineComponent, ref, watch } from '@vue/runtime-core'

export default defineComponent({
  name: 'QueryForm',
  props: {
    fields: {
      type: Array,
      default: () => [],
    },
    queryData: {
      type: Object,
      default: () => ({}),
    },
    span: {
      type: Number,
      default: 6,
    },
  },
  emits: ['update:queryData', 'getData'],
  setup (props, { emit }) {
    console.log(' queryform props', props.queryData)
    const formData = ref({})
    // formData.value = deepClone(props.queryData)
    const ruleForm = ref(null)

    watch(
      formData,
      (value) => {
        emit('update:queryData', value)
      },
      { deep: true },
    )
    watch(
      () => props.queryData,
      (value) => {
        if (formData.value !== value) {
          formData.value = deepClone(value)
        }
      },
      { deep: true },
    )
    // const formData = computed({
    //   get () {
    //     console.log('get formData')
    //     return props.queryData
    //   },
    //   set (value) {
    //     console.log('set formData', value)
    //     emit('update:queryData', value)
    //   },
    // })
    // const debounceSumbit = debounce
    function submitForm () {
      emit('getData')
    }
    function resetForm () {
      ruleForm.value.resetFields()
      emit('getData')
    }

    return {
      ruleForm,
      formData,
      submitForm,
      resetForm,
    }
  },
})
</script>

<style scoped lang="less">
</style>
